package kr.ac.mju.mdc.mjuapp.campusmap;

import java.util.Timer;
import java.util.TimerTask;

import kr.ac.mju.mdc.mjuapp.R;
import kr.ac.mju.mdc.mjuapp.network.NetworkManager;
import kr.ac.mju.mdc.mjuapp.util.PixelConverter;
import net.daum.mf.map.api.MapPOIItem;
import net.daum.mf.map.api.MapPoint;
import net.daum.mf.map.api.MapView;
import net.daum.mf.map.api.MapView.CurrentLocationTrackingMode;
import net.daum.mf.map.api.MapView.MapType;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

/**
 * @author davidkim
 *
 */
public class CampusmapActivity extends Activity implements OnClickListener, OnTouchListener,
		MapView.OpenAPIKeyAuthenticationResultListener, MapView.MapViewEventListener, MapView.CurrentLocationEventListener,
		MapView.POIItemEventListener {
	private final int LOADING_DIALOG = 10;
	private final int SLIDING_MOVE_LEFT = 11;
	private final int SLIDING_MOVE_RIGHT = 12;

	private boolean isOpened = false;

	private int leftMax = 0;
	private int leftMin = 0;

	private float oldX = 0;
	private float upOldX = 0;

	private Timer slidingTimer = null;
	private TimerTask slidingTimerTask = null;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			int what = msg.what;
			switch (what) {
			case SLIDING_MOVE_LEFT:
				slidingTimer = new Timer();
				slidingTimerTask = new TimerTask() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						handler.post(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								View contentView = findViewById(R.id.campusmap_content);
								// right to left
								if (contentView.getLeft() <= leftMin) {
									contentView.layout(0, contentView.getTop(), contentView.getRight(), contentView.getBottom());
									stopSlidingTimer();
									oldX = 0;
									upOldX = 0;
									isOpened = false;
									findViewById(R.id.campusmap_left_slidingbar).setClickable(false);
								} else {
									contentView.layout(contentView.getLeft() - 15, contentView.getTop(), contentView.getRight() - 15,
											contentView.getBottom());
								}
							}
						});
					}
				};
				slidingTimer.schedule(slidingTimerTask, 0, 5);
				break;
			case SLIDING_MOVE_RIGHT:
				slidingTimer = new Timer();
				slidingTimerTask = new TimerTask() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						handler.post(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								View contentView = findViewById(R.id.campusmap_content);
								// to right
								if (contentView.getLeft() >= leftMax) {
									contentView.layout(leftMax, contentView.getTop(), leftMax + contentView.getRight(),
											contentView.getBottom());
									stopSlidingTimer();
									oldX = 0;
									upOldX = 0;
									isOpened = true;
									findViewById(R.id.campusmap_left_slidingbar).setClickable(true);
								} else {
									contentView.layout(contentView.getLeft() + 15, contentView.getTop(), contentView.getRight() + 15,
											contentView.getBottom());
								}
							}
						});
					}
				};
				slidingTimer.schedule(slidingTimerTask, 0, 5);
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.campusmap_layout);
		// init
		init();
		//init layout
		initLayout();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case LOADING_DIALOG:
			Dialog progressDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			progressDialog.setContentView(R.layout.loading_progress);
			progressDialog.setCancelable(false);
			return progressDialog;
		default:
			return null;
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (isOpened)
			handler.sendEmptyMessage(SLIDING_MOVE_LEFT);
		else
			super.onBackPressed();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (NetworkManager.checkNetwork(getApplicationContext())) {
			int id = v.getId();
			MapView mapView = (MapView) findViewById(R.id.campusmap_mapview);
			switch (id) {
			case R.id.campusmap_btn_current_location:
				CurrentLocationTrackingMode trackingMode = mapView.getCurrentLocationTrackingMode();
				if (trackingMode == CurrentLocationTrackingMode.TrackingModeOff)
					mapView.setCurrentLocationTrackingMode(CurrentLocationTrackingMode.TrackingModeOnWithoutHeading);
				else if (trackingMode == CurrentLocationTrackingMode.TrackingModeOnWithoutHeading)
					mapView.setCurrentLocationTrackingMode(CurrentLocationTrackingMode.TrackingModeOnWithHeading);
				else {
					mapView.setCurrentLocationTrackingMode(CurrentLocationTrackingMode.TrackingModeOff);
					mapView.setShowCurrentLocationMarker(false);
				}
				break;
			case R.id.campusmap_btn_maptype:
				MapType mapType = mapView.getMapType();
				if (mapType == MapType.Standard)
					mapView.setMapType(MapType.Satellite);
				else if (mapType == MapType.Satellite)
					mapView.setMapType(MapType.Hybrid);
				else
					mapView.setMapType(MapType.Standard);
				break;
			case R.id.campusmap_btn_liberalarts:
				mapView.setMapCenterPointAndZoomLevel(MapPoint.mapPointWithGeoCoord(37.580002, 126.922607), 1, true);
				break;
			case R.id.campusmap_btn_natural:
				mapView.setMapCenterPointAndZoomLevel(MapPoint.mapPointWithGeoCoord(37.222363, 127.187813), 1, true);
				break;
			}
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_MOVE) {
			float currentX = event.getRawX();
			if (oldX == 0.)
				oldX = currentX;
			// drag
			View view = findViewById(R.id.campusmap_content);
			if (view.getLeft() <= leftMax && view.getLeft() >= leftMin) {
				view.layout((int) (view.getLeft() - (oldX - currentX)), view.getTop(), (int) (view.getRight() - (oldX - currentX)),
						view.getBottom());
				upOldX = oldX;
				oldX = currentX;
			}
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
			final float currentX = event.getRawX();
			// direction
			float direction = upOldX - currentX;
			if (isOpened)
				handler.sendEmptyMessage(SLIDING_MOVE_LEFT);
			else if (!isOpened)
				handler.sendEmptyMessage(SLIDING_MOVE_RIGHT);
			else if (direction > 0)
				handler.sendEmptyMessage(SLIDING_MOVE_LEFT);
			else if (direction < 0)
				handler.sendEmptyMessage(SLIDING_MOVE_RIGHT);
		}
		return false;
	}

	/**
	 * 
	 */
	private void init() {
		// init variables
		isOpened = false;
		oldX = 0;
		upOldX = 0;
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		PixelConverter converter = new PixelConverter(this);
		leftMax = (int) ((float)displaymetrics.widthPixels - converter.getWidth(135));
		leftMin = 0;
		// init mapview
		MapView mapView = (MapView) findViewById(R.id.campusmap_mapview);
		mapView.setDaumMapApiKey("18d7990adbaddb3f5c8def55be9cca28933c6dbf");
		mapView.setMapType(MapType.Hybrid);
		mapView.setZoomLevel(1, false);
		mapView.setCurrentLocationEventListener(this);
		mapView.setPOIItemEventListener(this);
		mapView.setOpenAPIKeyAuthenticationResultListener(this);
		mapView.setMapViewEventListener(this);
		// init listview liberal
		ContentResolver cr = getContentResolver();
		Cursor liberalCursor = cr
				.query(CampusmapContentProvider.CONTENT_URI_LIBERALARTS, null, null, null, CampusmapContentProvider.COL_ID);
		CampusmapBldgAdapter liberalAdapter = new CampusmapBldgAdapter(this, liberalCursor);
		liberalAdapter.notifyDataSetChanged();
		((ListView) findViewById(R.id.campusmap_liberalarts_building_listview)).setAdapter(liberalAdapter);
		((ListView) findViewById(R.id.campusmap_liberalarts_building_listview)).setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				((MapView) findViewById(R.id.campusmap_mapview)).removeAllPOIItems();
				MapPOIItem poiItem = new MapPOIItem();
				poiItem.setItemName(((TextView) view.findViewById(R.id.campusmap_row_bldg_name)).getText().toString());
				poiItem.setMapPoint(MapPoint.mapPointWithGeoCoord(
						Double.parseDouble(((TextView) view.findViewById(R.id.campusmap_row_bldg_latitude)).getText().toString()),
						Double.parseDouble(((TextView) view.findViewById(R.id.campusmap_row_bldg_longitude)).getText().toString())));
				poiItem.setMarkerType(MapPOIItem.MarkerType.RedPin);
				poiItem.setShowAnimationType(MapPOIItem.ShowAnimationType.NoAnimation);
				// poiItem.setShowCalloutBalloonOnTouch(false);
				poiItem.setTag(153);
				((MapView) findViewById(R.id.campusmap_mapview)).addPOIItem(poiItem);
				((MapView) findViewById(R.id.campusmap_mapview)).fitMapViewAreaToShowAllPOIItems();
				handler.sendEmptyMessage(SLIDING_MOVE_LEFT);
			}
		});
		// init listview natural
		Cursor naturalCursor = cr.query(CampusmapContentProvider.CONTENT_URI_NATURAL, null, null, null, CampusmapContentProvider.COL_ID);
		CampusmapBldgAdapter naturalAdapter = new CampusmapBldgAdapter(this, naturalCursor);
		naturalAdapter.notifyDataSetChanged();
		((ListView) findViewById(R.id.campusmap_natural_building_listview)).setAdapter(naturalAdapter);
		((ListView) findViewById(R.id.campusmap_natural_building_listview)).setSelection(0);
		((ListView) findViewById(R.id.campusmap_natural_building_listview)).setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				((MapView) findViewById(R.id.campusmap_mapview)).removeAllPOIItems();
				MapPOIItem poiItem = new MapPOIItem();
				poiItem.setItemName(((TextView) view.findViewById(R.id.campusmap_row_bldg_name)).getText().toString());
				poiItem.setMapPoint(MapPoint.mapPointWithGeoCoord(
						Double.parseDouble(((TextView) view.findViewById(R.id.campusmap_row_bldg_latitude)).getText().toString()),
						Double.parseDouble(((TextView) view.findViewById(R.id.campusmap_row_bldg_longitude)).getText().toString())));
				poiItem.setMarkerType(MapPOIItem.MarkerType.RedPin);
				poiItem.setShowAnimationType(MapPOIItem.ShowAnimationType.NoAnimation);
				// poiItem.setShowCalloutBalloonOnTouch(false);
				poiItem.setTag(153);
				((MapView) findViewById(R.id.campusmap_mapview)).addPOIItem(poiItem);
				((MapView) findViewById(R.id.campusmap_mapview)).fitMapViewAreaToShowAllPOIItems();
				handler.sendEmptyMessage(SLIDING_MOVE_LEFT);
			}
		});
		// set listener
		findViewById(R.id.campusmap_left_slidingbar).setOnTouchListener(this);
		findViewById(R.id.campusmap_sliding_btn).setOnTouchListener(this);
		findViewById(R.id.campusmap_btn_current_location).setOnClickListener(this);
		findViewById(R.id.campusmap_btn_maptype).setOnClickListener(this);
		findViewById(R.id.campusmap_btn_liberalarts).setOnClickListener(this);
		findViewById(R.id.campusmap_btn_natural).setOnClickListener(this);
	}
	/**
	 * 
	 */
	private void initLayout(){
		PixelConverter converter = new PixelConverter(this);
		RelativeLayout.LayoutParams rParams = null;
		rParams = (LayoutParams) findViewById(R.id.campusmap_sub_layout).getLayoutParams();
		rParams.rightMargin = converter.getWidth(135);
		findViewById(R.id.campusmap_sub_layout).setLayoutParams(rParams);
	}

	/**
	 * 
	 */
	private void stopSlidingTimer() {
		if (slidingTimerTask != null) {
			slidingTimerTask.cancel();
			slidingTimerTask = null;
		}
		if (slidingTimer != null) {
			slidingTimer.purge();
			slidingTimer.cancel();
			slidingTimer = null;
		}
	}

	/**
	 * net.daum.mf.map.api.MapView.POIItemEventListener
	 */
	@Override
	public void onCalloutBalloonOfPOIItemTouched(MapView mapView, MapPOIItem poiItem) {
		// TODO Auto-generated method stub
		String title = poiItem.getItemName();
		ContentResolver cr = getContentResolver();
		Cursor cursor = cr.query(CampusmapContentProvider.CONTENT_URI_OFFICE, null, CampusmapContentProvider.COL_BLDG_NAME + " = '" + title
				+ "'", null, CampusmapContentProvider.COL_ID);
		int size = cursor.getCount();
		if(size > 0){
			CampusmapDialog dialog = new CampusmapDialog(this, cursor);
			dialog.setTitle(poiItem.getItemName());
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		}		
	}

	@Override
	public void onDraggablePOIItemMoved(MapView arg0, MapPOIItem arg1, MapPoint arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPOIItemSelected(MapView arg0, MapPOIItem arg1) {
		// TODO Auto-generated method stub

	}

	/**
	 * net.daum.mf.map.api.MapView.CurrentLocationEventListener
	 */
	@Override
	public void onCurrentLocationDeviceHeadingUpdate(MapView arg0, float arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCurrentLocationUpdate(MapView arg0, MapPoint arg1, float arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCurrentLocationUpdateCancelled(MapView arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCurrentLocationUpdateFailed(MapView arg0) {
		// TODO Auto-generated method stub

	}

	/**
	 * net.daum.mf.map.api.MapView.MapViewEventListener
	 */
	@Override
	public void onMapViewCenterPointMoved(MapView arg0, MapPoint arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMapViewDoubleTapped(MapView arg0, MapPoint arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMapViewInitialized(MapView mapView) {
		// TODO Auto-generated method stub
		mapView.setCurrentLocationTrackingMode(CurrentLocationTrackingMode.TrackingModeOnWithoutHeading);
	}

	@Override
	public void onMapViewLongPressed(MapView arg0, MapPoint arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMapViewSingleTapped(MapView arg0, MapPoint arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMapViewZoomLevelChanged(MapView arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	/**
	 * net.daum.mf.map.api.MapView.OpenAPIKeyAuthenticationResultListener
	 */
	@Override
	public void onDaumMapOpenAPIKeyAuthenticationResult(MapView arg0, int arg1, String arg2) {
		// TODO Auto-generated method stub

	}
}
/* end of file */
